<template>
  <div class="borrow-calendar w-1300px overflow-hidden">
    <div class="borrow-calendar-btns text-right">
      <LeftOutlined @click="onLeftMove" :style="{color:leftBtnColor}"/>
      <RightOutlined @click="onRightMove" :style="{color:rightBtnColor}"/>
    </div>
    <a-carousel :dots="false" ref="carouselRef" :beforeChange="onBeforeChangeCarousel">
      <div class="month-page  grid-cols-3 gap-5 min-w-1300px"  v-for="(page, monthIndex) in monthsList" :key="monthIndex">
        <div class="month max-h-365px py-15px bg-white" v-for="item in page" :key="item.id">
          <div class="text-center font-bold font-size-18px">{{ item.year }}年 {{ item.month }}月</div>
          <div>
            <div class="grid grid-cols-7 gap-1 py-5px px-15px mb-15px border-b-1px color-#8C8C8C text-center">
              <div>一</div>
              <div>二</div>
              <div>三</div>
              <div>四</div>
              <div>五</div>
              <div>六</div>
              <div>日</div>
            </div>
            <div class="grid grid-cols-7 gap-2px px-15px text-center">
              <div
                v-for="day in item.monthlyDateList"
                :key="day"
                class="h-40px line-height-40px border-color-#e9e9e9 font-size-16px"
                :class="[{ 'border-t-4px': day, 'day-active': getDayActive(day) }]"
                @click="handleDayClick(day)"
              >
                {{ day.substring(8) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-carousel>
    <a-modal v-model:open="openBorrowInfo" title="借用详情" >
      <div class="px-25px pt-15px font-size-16px">
        <p>部门：{{ borrowInfoObj.dept }}</p>
        <p>申请人：{{ borrowInfoObj.proposer }}</p>
        <p>用途：{{ borrowInfoObj.use }}</p>
        <p>备注：{{ borrowInfoObj.remeark }}</p>
      </div>
      <template #footer>
        <a-button key="back" @click="handleCancelBorrowInfo">关闭</a-button>
      </template>
    </a-modal>
  </div>

</template>
<script setup lang="ts">
  import { ref, inject, onMounted } from 'vue';
  import { LeftOutlined, RightOutlined } from '@ant-design/icons-vue';
  import { buildUUID } from '/@/utils/uuid';
  const dayjs: any = inject('$dayjs');
  

  interface MonthData {
    year: string;
    month: string;
    id: string;
    monthlyDateList: string[];
  }
  
  const dateList = [
    {
      startDate: '2023-09-01',
      endDate: '2023-09-10',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2023-10-01',
      endDate: '2023-10-10',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2023-11-08',
      endDate: '2023-11-08',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2023-11-12',
      endDate: '2023-11-14',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2023-12-01',
      endDate: '2023-12-10',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2023-12-22',
      endDate: '2023-12-25',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2024-01-01',
      endDate: '2024-01-10',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2024-04-01',
      endDate: '2024-04-10',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2024-04-18',
      endDate: '2024-04-22',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2024-04-29',
      endDate: '2024-05-15',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2024-05-20',
      endDate: '2024-06-03',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2024-09-20',
      endDate: '2024-09-26',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2024-07-15',
      endDate: '2024-07-16',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
    {
      startDate: '2024-10-09',
      endDate: '2024-10-15',
      dept: '试制科',
      proposer:"王丽华",
      use:"碰撞试验",
      remeark:"测试碰撞试验，车辆点检需要重点检查"
    },
  ];

  // 日历左右切换
  const monthPageIndex = ref<number>(0);
  const leftBtnColor = ref<string>("");
  const rightBtnColor = ref<string>("");
  const carouselRef = ref();
  const onLeftMove = () =>{
    rightBtnColor.value = "";
    if (monthPageIndex.value <= 0) return;
    carouselRef.value.prev()
  }
  // 	切换面板的回调
  const onRightMove = () =>{
    leftBtnColor.value = "";
    if (monthPageIndex.value >= monthsList.length - 1) return;
    carouselRef.value.next()
  }
  function onBeforeChangeCarousel(from, to){
    if (to <= 0) {
      leftBtnColor.value = "#d9d9d9";
    }
    if (to >= monthsList.length - 1) {
      rightBtnColor.value = "#d9d9d9";
    }
    monthPageIndex.value = to;
  }

  // 获取借用日期
  const dateRange = [];
  const getBorrowDate = () => {
    if (dateList.length <= 0) return;
    for (let i = 0; i < dateList.length; i++) {
      const item = dateList[i];
      // 获取两个日期之间的所有日期，包括起始和结束日期
      let currentDate = dayjs(item.startDate);
      const endDate = dayjs(item.endDate);
      while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {
        dateRange.push(Object.assign({}, item, { date: currentDate.format('YYYY-MM-DD') })); 
        // 增加一天
        currentDate = currentDate.add(1, 'day'); 
      }
    }
  };
  // 生成最开始的借用日期和最后的借用日期之间的所有日期
  const monthsList:any = [];
  function generateMonthlyDates() {
    if (dateList.length <= 0) return;
    // 获取最开始的借用日期和最后的借用日期
    const startDate = dayjs(dateList[0].startDate);
    const endDate = dayjs(dateList[dateList.length - 1].endDate);
    // 如果最开始的借用日期大于最后的借用日期，则返回
    if (startDate.isAfter(endDate)) return;
    let months: MonthData[] = [];
    // 获取每月的第一天
    let monthlyFirstDay = startDate.clone();
    console.log(monthlyFirstDay)
    // 当月在 monthsList 中的索引
    let currentMonthIndexInMonths = 0;
    while (monthlyFirstDay.isBefore(endDate)) {
      const monthlyDateList: string[] = [];
      // 获取每月天数
      const daysInMonth = monthlyFirstDay.daysInMonth();
      for (let day = 1; day <= daysInMonth; day++) {
        const formattedDay = monthlyFirstDay.date(day).format('YYYY-MM-DD');
        monthlyDateList.push(formattedDay);
        
        // 获取当月在 monthsList 中的索引
        if (dayjs().format('YYYY-MM') == monthlyFirstDay.format('YYYY-MM')) {
          monthPageIndex.value = currentMonthIndexInMonths;
        }
      }
      // 获取每月的第一天是星期几，并在日期列表的前面添加空数据
      const firstDayOfWeek = monthlyFirstDay.startOf('month').day();
      monthlyDateList.unshift(...new Array(firstDayOfWeek).fill(''));
      months.push({
        year: monthlyFirstDay.format('YYYY'),
        month: monthlyFirstDay.format('MM'),
        id: buildUUID(),
        monthlyDateList,
      });
      if (months.length >= 6) {
        currentMonthIndexInMonths ++ ;
        monthsList.push(months);
        months = [];
      };
      monthlyFirstDay = monthlyFirstDay.add(1, 'month');
    }
      console.log(months)
      console.log(months.length % 6)
    // 处理剩余不足6个月的情况
    if (months.length > 0) {
      monthsList.push(months);
    }
    
    getBorrowDate();
  }

  
  // 高亮借车日期
  const getDayActive = (day) => {
    if (!day) return false;
    // 判断借用日期是否有传值日期
    let borrowObj: object | undefined = dateRange.find((item) => item.date === day);
    const isBorrow = borrowObj ? true : false;
    if (!isBorrow) return false;
    if (borrowObj) {
      Object.assign(borrowObj, { isBorrow });
    }
    return borrowObj;
  };

  // 点击高亮接车日期
  const openBorrowInfo = ref<boolean>(false);
  const borrowInfoObj = ref<object>();
  const handleDayClick = (day) => {
    const borrowObj = getDayActive(day);
    if(!borrowObj) return;
    borrowInfoObj.value = borrowObj;
    openBorrowInfo.value = true;
  }
  const handleCancelBorrowInfo = () => {
    openBorrowInfo.value = false;
  }

  generateMonthlyDates();
  onMounted(()=>{
    // 跳转到当前日期所在的面板
    carouselRef.value.goTo(monthPageIndex.value, true);
  })
</script>
<style scoped lang="less">
  .borrow-calendar{
    margin:0 auto;
  }
  .borrow-calendar-btns{
    font-size: 35px;
    cursor: pointer;
  }
  .month-page{
    display: grid !important;
  }
  .month {
    border: 4px solid #f4f4f4;
    border-radius: 2px;
  }
  .day-active {
    cursor: pointer;
    border-color: rgba(37, 199, 212, 1);
    background-color: rgba(205, 230, 227, 1);
  }
</style>
